<?php
/**
 * Google翻译的API
 * @see 使用请参考最底部写法！
 * @editor Summer.Hu(blog:http://blog.hucde.com)
 */
class Google_translate_API
{
	public  $out = "";
	public  $text = "";
	public $fromLanguage="zh";//默认英文
	public $toLanguage="en";//默认法文
	public $opts = array("text" => "", "language_pair" => "");
	function setValues($text)
	{
		if($text != "")
		$fromLanguage=$this->fromLanguage;
		$toLanguage=$this->toLanguage;
		$this->opts["text"] = $text;
		if($fromLanguage != "" && $toLanguage != "")
		$this->opts["language_pair"] = $fromLanguage."|".$toLanguage;
	}
	function getValues()
	{
		$this->out = "";
		$size = 480;
		if (strlen($this->opts['text']) >  $size)
		{
			$t = strlen($this->opts['text']);
			
			//计算划分的页数
			$num = ($t>$size) ? ceil($t/$size) : 1;
			for($i=0;$i<$num;$i++)
			{
				$str = mb_substr($this->opts['text'],$i*$size,$size);
			    $google_translator_url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($str)."&langpair=".urlencode($this->opts['language_pair'])."";
			    $response = $this->postPage(array("url" => $google_translator_url));
			    $resValues .= $response['responseData']['translatedText'];
			}
			
		}
		else
		{
			$google_translator_url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($this->opts['text'])."&langpair=".urlencode($this->opts['language_pair'])."";
			//$google_translator_url = " http://trans.netat.net/trans.php?sen=".urlencode($this->opts['text'])."&lang=".urlencode($this->opts['language_pair'])."";
 			
			$response = $this->postPage(array("url" => $google_translator_url));
			$resValues = $response['responseData']['translatedText'];
		}
 
		$this->out = $resValues;
 
		return $this->out;
	}
	function postPage($opts)
	{
		$response = "";
		if($opts["url"] != "") {
			$ch = curl_init($opts["url"]);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$response = curl_exec($ch);
			if(curl_errno($ch))
			$response = "";
			curl_close($ch);
			$decoded = json_decode( $response, true );
		}
		return $decoded;
	}
}
?>